package com.tc.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufUtil;

import static io.netty.util.internal.StringUtil.NEWLINE;

/**
 * @Auther: tianchao
 * @Date: 2022/2/11 14:50
 * @Description: netty 的 ByteBuf
 */
public class TestByteBuf {
    public static void main(String[] args) {
        //test1();
        final ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(20);
        buffer.writeBytes(new byte[]{1,2,3,4});
        buffer.writeInt(5);
        buffer.writeInt(6);
        log(buffer);
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        System.out.println(buffer.readByte());
        log(buffer);
        //读取一下整数5  还想重复读取
        buffer.markReaderIndex();
        System.out.println(buffer.readInt());
        log(buffer);
        buffer.resetReaderIndex();
        log(buffer);

    }

    private static void test1() {
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        System.out.println(buf.getClass());
        log(buf);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 1; i++) {
            sb.append("a");
        }
        buf.writeBytes(sb.toString().getBytes());
        log(buf);
    }


    private static void log(ByteBuf byteBuf){
        int length = byteBuf.readableBytes();
        int rows =length / 16 + (length%15 ==0?0:1)+4;
        StringBuilder buf = new StringBuilder(rows*88*2)
                .append("read index:").append(byteBuf.readerIndex())
                .append(" write index:").append(byteBuf.writerIndex())
                .append(" capacity:").append(byteBuf.capacity())
                .append(NEWLINE);
        ByteBufUtil.appendPrettyHexDump(buf,byteBuf);
        System.out.println(buf.toString());
    }
}
